﻿using System;

namespace BinarySearch
{
    class BinarySearch
    {
        static int Search(int[] array, int number)
        {
            int leftIndex = 0,
                rightIndex = array.Length - 1,
                middleIndex = 0;
            bool isFound = false;

            while (leftIndex <= rightIndex)
            {
                middleIndex = leftIndex + (rightIndex - leftIndex) / 2;

                if (array[middleIndex] < number)
                {
                    leftIndex = middleIndex + 1;
                }
                else if (array[middleIndex] > number)
                {
                    rightIndex = middleIndex - 1;
                }
                else
                {
                    isFound = true;
                    break;
                }
            }
            return isFound ? middleIndex : -1;
        }

        static void Main()
        {
            int[] numbers;
            int result, number, arrayLength;
            Console.Write("Please enter the length of your array: ");
            arrayLength = int.Parse(Console.ReadLine());
            Console.Write("Enter the number: ");
            number = int.Parse(Console.ReadLine());
            numbers = new int[arrayLength];
            for (int index = 0; index < arrayLength; index++)
            {
                Console.Write("Index [{0}]: ", index);
                numbers[index] = int.Parse(Console.ReadLine());
            }
            result = Search(numbers, number);
            Console.WriteLine(result);
        }
    }
}